package cn.sinata.wanglin.neighbor.fragment;

import android.content.DialogInterface;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DensityUtil;
import com.xilada.xldutils.utils.DialogUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.PushDao;
import cn.sinata.wanglin.neighbor.activity.ChatActivity;
import cn.sinata.wanglin.neighbor.activity.FindFriendActivity;
import cn.sinata.wanglin.neighbor.activity.MineCircleActivity;
import cn.sinata.wanglin.utils.ImageUtil;

/**
 * description：
 * Created by kaihongwu on 2016/12/05 下午 12:00
 */
public class NeighborFragment extends BaseLazyFragment implements ViewPager.OnPageChangeListener,EMMessageListener{

    @BindView(R.id.mTabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.mViewPager)
    ViewPager mViewPager;
    @BindView(R.id.sv_action)
    SimpleDraweeView sv_action;
    @BindView(R.id.circleUnreadView)
    TextView circleUnreadView;
    @BindView(R.id.msgUnreadView)
    TextView msgUnreadView;
    @BindView(R.id.contactUnreadView)
    TextView contactUnreadView;
    private String account;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_neighbor;
    }

    @Override
    protected void onFirstVisibleToUser() {
        mTabLayout.setTabTextColors(ContextCompat.getColor(context,R.color.gray_color_aab)
                ,ContextCompat.getColor(context,R.color.yellow_color_81d));
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(context,R.color.yellow_color_81d));

        EMClient.getInstance().chatManager().addMessageListener(this);
        account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);

        mViewPager.setAdapter(new FragmentAdapter(getChildFragmentManager()));
        mViewPager.addOnPageChangeListener(this);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.setCurrentItem(1);
        sv_action.setImageURI(Uri.parse("res:///"+R.mipmap.neighbor_add));
        sv_action.getLayoutParams().width = DensityUtil.dip2px(context,30);
        sv_action.getLayoutParams().height = DensityUtil.dip2px(context,30);
        unReadSet();
    }

    void unReadSet(){
        if (MyApplication.circleUnRead > 0) {
            circleUnreadView.setVisibility(View.VISIBLE);
        } else {
            circleUnreadView.setVisibility(View.INVISIBLE);
        }
        int count = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        if (count > 0) {
            msgUnreadView.setVisibility(View.VISIBLE);
        } else {
            msgUnreadView.setVisibility(View.INVISIBLE);
        }

        int count1 = PushDao.getInstance(context).getUnReadNum(account,Constant.Push.CMD_MEG_TYPE_F);

        if (count1>0) {
            contactUnreadView.setVisibility(View.VISIBLE);
        } else {
            contactUnreadView.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onVisibleToUser() {
        unReadSet();
    }

    @Override
    protected void onInvisibleToUser() {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position == 2) {
            String headUrl = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
            sv_action.setImageURI(ImageUtil.parseImageUri(headUrl));
            sv_action.getLayoutParams().width = DensityUtil.dip2px(context,40);
            sv_action.getLayoutParams().height = DensityUtil.dip2px(context,40);
            sv_action.requestLayout();
        } else {
            sv_action.getLayoutParams().width = DensityUtil.dip2px(context,30);
            sv_action.getLayoutParams().height = DensityUtil.dip2px(context,30);
            sv_action.setImageURI(Uri.parse("res:///"+R.mipmap.neighbor_add));
            sv_action.requestLayout();
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {
        for (EMMessage emMessage : list) {
            if (emMessage.getType() == EMMessage.Type.CMD) {
                EMCmdMessageBody messageBody = (EMCmdMessageBody) emMessage.getBody();
                String action = messageBody.action();
                if (action.equals(Constant.Push.CMD_MEG_TYPE_FK) || action.equals(Constant.Push.CMD_MEG_TYPE_G)
                        ||action.equals(Constant.Push.CMD_MEG_TYPE_F)|| action.equals(Constant.Push.CMD_MEG_TYPE_GA)) {
                    if (getActivity() != null && !isDetached()) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                contactUnreadView.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    public void onMessageReadAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageDeliveryAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }

    private class FragmentAdapter extends FragmentStatePagerAdapter{

        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        String[] titles = {"附近","聊天","圈子","通讯录"};

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return new NeighborNearbyFragment();
            } else if (position == 1) {
                ConversationListFragment fragment = new ConversationListFragment();
                fragment.setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {
                    @Override
                    public void onListItemClicked(EMConversation conversation) {
                        int chatType = EaseConstant.CHATTYPE_SINGLE;
                        if (conversation.isGroup()) {
                            chatType = EaseConstant.CHATTYPE_GROUP;
                        }
                        ActivityUtil.create(context)
                                .go(ChatActivity.class)
                                .put(EaseConstant.EXTRA_CHAT_TYPE,chatType)
                                .put(EaseConstant.EXTRA_USER_ID,conversation.getUserName())
                                .start();
                    }

                    @Override
                    public boolean onListItemLongClicked(final EMConversation conversation) {
                        DialogUtils.createNoticeDialog(context, "请注意", "确定要删除当前聊天记录么（删除后不可恢复）？", "确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                EMClient.getInstance().chatManager().deleteConversation(conversation.getUserName(),true);
                            }
                        });
                        return true;
                    }
                });

                return fragment;
            } else if (position == 2) {
                return new CircleFragment();
            } else if (position == 3) {
                return new ContactsFragment();
            }
            return new NeighborNearbyFragment();
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }

    @OnClick(R.id.sv_action)
    void onRightClick(){
        //圈子
        if (mViewPager.getCurrentItem() == 2) {
            String userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
            ActivityUtil.create(context)
                    .go(MineCircleActivity.class)
                    .put("id",userId)
                    .start();
        } else {
            ActivityUtil.create(context)
                    .go(FindFriendActivity.class)
                    .start();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mViewPager != null) {
            mViewPager.removeOnPageChangeListener(this);
        }
    }
}
